package com.cbgolf.oa.activity.coupon;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.CouponBean;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.EnumUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.AutoResizeTextView;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by lq on 2017/9/5.
 */

public class CouponHistoryActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    //top
    @ViewInject(R.id.topBack_ll)
    private View topBack;
    @ViewInject(R.id.title_tv)
    private TextView topTitle;
    //bady
    @ViewInject(R.id.a_coupon_history_refresh_layout)
    private SwipeRefreshLayout refreshLayout;
    @ViewInject(R.id.a_coupon_history_listview)
    private ListView listView;
    //error
    @ViewInject(R.id.g_error_ll)
    private View errorView;
    @ViewInject(R.id.g_error_tv)
    private TextView errorTv;
    @ViewInject(R.id.g_error_reload_tv)
    private TextView reLoadTv;
    @ViewInject(R.id.g_error_loading_tv)
    private TextView loadingTv;
    //var
    private MyBaseAdapter<CouponBean> adapter;
    private List<CouponBean> listData = new ArrayList<>();
    private boolean isLoading;

    Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_coupon_history);
    }

    @Override
    protected void findViews() {
        x.view().inject(this);
    }

    @Override
    protected void setViews() {
        topTitle.setText("发放历史");
        adapter = new MyBaseAdapter<CouponBean>(R.layout.item_coupon_history,
                context, listData) {
            @Override
            public View getView(int position, View view, ViewGroup parent, CouponBean m_coupon) {
                String pushDate = m_coupon.pushDate;
                setText(R.id.item_coupon_time_tv, "发放时间" + DateUtil.stampToDate(pushDate, DateUtil.formatWithbias));
                AutoResizeTextView numTv = (AutoResizeTextView) view.findViewById(R.id.item_coupon_num_tv);
                String moneyNum = m_coupon.parValue;
                if (!Util.isNull(moneyNum)) {
                    try {
                        BigDecimal bd = new BigDecimal(moneyNum);
                        double d = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        DecimalFormat df = new DecimalFormat("#.##");
                        moneyNum = df.format(d);
                    } catch (Exception e) {

                    }
                }
                numTv.setText(Util.isNull(moneyNum) ? "" : moneyNum);

//                setText(R.id.item_coupon_num_tv, String.valueOf(m_coupon.parValue));
                String type = EnumUtil.getCouponType(m_coupon.couponType);
                setText(R.id.item_coupon_type_tv, type);
                setText(R.id.item_coupon_name_tv, m_coupon.courseName);
                int lowest = m_coupon.lowestConsumption;
                setText(R.id.item_coupon_limit_tv, "1.订" +
                        "场满" + lowest + "元可使用");
                String start = "";
                String end = "";
                if (null != m_coupon.availabilityPeriod) {
                    start = m_coupon.availabilityPeriod.start;
                    end = m_coupon.availabilityPeriod.end;
                }
                try {
                    long en = Long.parseLong(end);
                    if (en > System.currentTimeMillis()) {
                        Log.e("end->-current-------", "yes");
                        String isNoDisable = m_coupon.isReceivable;
                        int allNum = m_coupon.quantity;
                        int outNum = m_coupon.receivedQuantity;
                        if (0 != allNum && allNum == outNum) {
                            setText(R.id.item_coupon_state_tv, "已领完");
                        } else if (Util.isNull(isNoDisable) || String.valueOf(false).equals(isNoDisable)) {
                            setText(R.id.item_coupon_state_tv, "已禁用");
                        } else {
                            setText(R.id.item_coupon_state_tv, "");
                        }
                    } else {
                        Log.e("end->-current-------", "no");
                        setText(R.id.item_coupon_state_tv, "已过期");
                    }
                } catch (Exception e) {
                }

                setText(R.id.item_coupon_duration_tv, "2.有效期" + DateUtil.stampToDate(start, DateUtil.formatYMDWithPoint)
                        + "-" + DateUtil.stampToDate(end, DateUtil.formatYMDWithPoint));

                return view;
            }
        };
        listView.setAdapter(adapter);
        // 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
        refreshLayout.setColorSchemeResources(R.color.bg_blue, R.color.text_gray,
                R.color.white, R.color.bg_blue);
//        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        refreshLayout.setDistanceToTriggerSync(300);// 设置手指在屏幕下拉多少距离会触发下拉刷新
        refreshLayout.setSize(SwipeRefreshLayout.LARGE);
        refreshLayout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.white));
//        refreshLayout.setPageCount(pageSize);

    }

    @Override
    protected void setListener() {
        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        refreshLayout.setOnRefreshListener(this);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (listView.getAdapter() != null && listView.getLastVisiblePosition() == (listView.getAdapter().getCount() - 1)
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (!isLoading) {
                        page++;
                        loadMore();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

    }

    @Override
    protected void loadData() {
        super.loadData();
        getData();
    }

    private void loadMore() {
        isLoading = true;
        if (!Util.isNetWorkConnected()) {
            showError(LOADMORE);
            return;
        }
        String url = WebAPI.coupons_history_get;
        Map<String, String> map = new HashMap<>();
        map.put("pageSize", pageSize + "");
        map.put("currentPage", page + "");
        String token = "";
        if (null != UserData.getUser()) {
            token = UserData.getUser().getToken();
        }
        map.put("token", token);
//        AnimaUtil.showLoading(context);
        Web.getOK(url, map, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                if (200 != response.statusCode) {
                    showError(LOADMORE);
                    return;
                }
                if (Util.isNull(response.result)) {
                    showError(LOADMORE);
                    return;
                }
                List<CouponBean> list = null;
                try {
                    JSONObject json = JSON.parseObject(response.result);
                    list = JSON.parseArray(json.getString("content"), CouponBean.class);
                } catch (Exception e) {
                    showError(LOADMORE);
                    return;
                }
                if (null != list && list.size() > 0) {
                    showData();
                    listData.addAll(list);
                    adapter.updateUI();
                } else {
                    showError(LOADMORE);
                }
            }

        }));
    }

    private void getData() {
        isLoading = true;
        if (!Util.isNetWorkConnected()) {
            showError(NONET);
            return;
        }
        String url = WebAPI.coupons_history_get;
        Map<String, String> map = new HashMap<>();
        map.put("pageSize", pageSize + "");
        map.put("currentPage", "0");
        String token = null == UserData.getUser() ? "" : UserData.getUser().getToken();
        map.put("token", token);
        showLoading();
        Web.getOK(url, map, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                if (200 != response.statusCode) {
                    showError(NETERROR);
                    return;
                }
                if (Util.isNull(response.result)) {
                    showError(NODATA);
                    return;
                }
                List<CouponBean> list = null;
                try {
                    JSONObject json = JSON.parseObject(response.result);
                    list = JSON.parseArray(json.getString("content"), CouponBean.class);
                } catch (Exception e) {
                    showError(NETERROR);
                    return;
                }
                if (null != list && list.size() > 0) {
                    showData();
                    listData.clear();
                    listData.addAll(list);
                    adapter.updateUI();
                } else {
                    showError(NODATA);
                }
            }
        }));
    }

    private void showLoading() {
        if (!refreshLayout.isRefreshing())
            AnimaUtil.showLoading(context, loadingTv);

    }

    private void showData() {
        stopLoading();
        if (null != refreshLayout) {
            refreshLayout.setRefreshing(false);
        }
        isLoading = false;
        refreshLayout.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }

    private final int NONET = 1;
    private final int NETERROR = 2;
    private final int NODATA = 3;
    private final int LOADMORE = 4;


    private int page = 0;
    private int pageSize = 15;

    private void showError(int type) {
        stopLoading();
        if (null != refreshLayout) {
            refreshLayout.setRefreshing(false);
        }
        isLoading = false;
        if (type == LOADMORE && page > 0) {
            page--;
        }
        if (listData.size() > 0) {
            return;
        }
        refreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
        switch (type) {
            case NONET:
                errorTv.setText(getResources().getString(R.string.no_net));
                break;
            case NETERROR:
                errorTv.setText(getResources().getString(R.string.net_error));
                break;
            case NODATA:
                errorTv.setText(getResources().getString(R.string.no_data));
                break;
        }


    }

    @Override
    public void onRefresh() {
        if (!isLoading) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getData();

                }
            }, 200);
        } else {
            if (null != refreshLayout) {
                refreshLayout.setRefreshing(false);
            }
        }
    }

}
